/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kimstore.gui.report;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.kimstore.bean.Batch;
import com.kimstore.bean.Item;
import com.kimstore.bean.Order;
import com.kimstore.bean.Product;
import com.kimstore.bean.Staff;
import com.kimstore.dao.ProductDao;
import com.kimstore.factory.DaoFactory;
import com.kimstore.utilities.DateUtil;
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class GenerateReportController {

    private GenerateReportWindow window = null;
    private ProductDao productDao = null;

    public GenerateReportController() {
        productDao = DaoFactory.getInstance().getProductDao();
    }

    public void fromWindow(int type, String dest, Date startDate, Date endDate) {
        try {
            File file = generate(type, dest, startDate, endDate);
            Desktop desktop;
            if (Desktop.isDesktopSupported()) {
                desktop = Desktop.getDesktop();
                try {
                    desktop.open(file);
                } catch (IOException e) {
                }
            }
        } catch (DocumentException ex) {
            Logger.getLogger(GenerateReportController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GenerateReportController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void displayWindow(int type) {
        window = new GenerateReportWindow(this, type);
        window.showWindow();
    }

    public File generate(int type, String dest, Date startDate, Date endDate)
            throws DocumentException, IOException {
        String label = (type == 0 ? "Gross Income" : type == 1 ? "Net Income" : type == 2 ? "Total Repair" : type == 3 ? "Performance" : type == 4 ? "Staff Movement" : "Sales") + " Report";
        String filename = dest + "/KimStore " + label + " " + DateUtil.formatDate(startDate, DateUtil.REPORT_DATE) + " to " + DateUtil.formatDate(endDate, DateUtil.REPORT_DATE) + ".pdf";
        String header = type != 3 ? label + " (" + DateUtil.formatDate(startDate, DateUtil.JXDATE) + " - " + DateUtil.formatDate(endDate, DateUtil.JXDATE) + ")" : label;

        endDate.setHours(23);
        endDate.setMinutes(59);
        endDate.setSeconds(59);
        
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(filename));

        document.open();

        Image logo = Image.getInstance("src/com/kimstore/resources/images/logo_with_name.png");
        logo.setAlignment(Element.ALIGN_CENTER);
        document.add(logo);

        Paragraph par1 = new Paragraph(header);
        par1.setAlignment(Element.ALIGN_CENTER);
        document.add(par1);

        PdfPTable table = null;
        List<Product> products = null;
        Product p = null;
        /* Gross Sales and Net Income */
        if (type < 2) {

            
                products = productDao.getGrossSales(startDate, endDate);
                float totalCost = 0;

            if (type == 0) {

                table = new PdfPTable(4);
                table.setSpacingBefore(10f);
                
                table.setWidths(new int[] {5, 35, 10, 20});

                table.addCell(new PdfPCell(new Phrase("#"))).setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell("Product Name");
                table.addCell(new PdfPCell(new Phrase("Quantity"))).setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell("Amount Made");
            
                for (int i = 0, size = products.size(); i < size; i++) {
                    p = products.get(i);
                    table.addCell(new PdfPCell(new Phrase(i+1+""))).setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(p.getName());
                    table.addCell(new PdfPCell(new Phrase(p.getAvailableStocks() + ""))).setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(new PdfPCell(new Phrase(p.getTotalPriceSold() + ""))).setHorizontalAlignment(Element.ALIGN_RIGHT);
                    totalCost += p.getTotalPriceSold();
                }
                
                PdfPCell cell = new PdfPCell(new Phrase("Total: "));
                cell.setColspan(3);
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                
                table.addCell(cell);
                cell = new PdfPCell(new Phrase((totalCost) + ""));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                table.addCell(cell);             
            } else {
                double totalPurchaseCost = 0;
                
                par1 = new Paragraph("Stocks Arrival");
                par1.setAlignment(Element.ALIGN_CENTER);
                document.add(par1);
                
                table = new PdfPTable(5);
                table.setSpacingBefore(10);
                table.setSpacingAfter(10f);

                
                table.setWidths(new int[] {5, 25, 25, 20, 20});

                table.addCell(new PdfPCell(new Phrase("#"))).setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell("Batch Number");
                table.addCell(new PdfPCell(new Phrase("Date"))).setHorizontalAlignment(Element.ALIGN_CENTER);

                table.addCell("Staff");
                table.addCell("Cost");
                
                List<Batch> batches = DaoFactory.getInstance().getBatchDao().findByDate(startDate, endDate);
                
                int i = 0;
                
                for(Batch batch:batches) {
                    table.addCell(new PdfPCell(new Phrase(++i+""))).setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(batch.getNumber() + "");
                    table.addCell(new PdfPCell(new Phrase(batch.getDateReceived() + ""))).setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(batch.getReceivedBy().getName());
                    table.addCell(new PdfPCell(new Phrase(batch.getPurchaseCost() + ""))).setHorizontalAlignment(Element.ALIGN_RIGHT);
                    
                    totalPurchaseCost += batch.getPurchaseCost();
                }
                
                                
                PdfPCell cell = new PdfPCell(new Phrase("Total: "));
                cell.setColspan(4);
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                
                table.addCell(cell);
                cell = new PdfPCell(new Phrase((totalPurchaseCost) + ""));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                table.addCell(cell);     

                document.add(table);
                
                
                par1 = new Paragraph("Items Sold");
                par1.setAlignment(Element.ALIGN_CENTER);
                document.add(par1);
                
                table = new PdfPTable(4);
                table.setSpacingBefore(10f);
                table.setSpacingAfter(10f);
                
                table.setWidths(new int[] {5, 35, 10, 20});

                table.addCell(new PdfPCell(new Phrase("#"))).setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell("Product Name");
                table.addCell(new PdfPCell(new Phrase("Quantity"))).setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell("Amount Made");
            
                i = 0;
                
                for(Product product: products) {
                    table.addCell(new PdfPCell(new Phrase(++i+""))).setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(product.getName());
                    table.addCell(new PdfPCell(new Phrase(product.getAvailableStocks() + ""))).setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(new PdfPCell(new Phrase(product.getTotalPriceSold() + ""))).setHorizontalAlignment(Element.ALIGN_RIGHT);
                    totalCost += product.getTotalPriceSold();
                }
                
                cell = new PdfPCell(new Phrase("Total: "));
                cell.setColspan(3);
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                
                table.addCell(cell);
                cell = new PdfPCell(new Phrase((totalCost) + ""));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                table.addCell(cell);     
                
                document.add(table);
                
                par1 = new Paragraph("Summary");
                par1.setAlignment(Element.ALIGN_CENTER);
                document.add(par1);
                
                table = new PdfPTable(2);
                table.setSpacingBefore(10f);
                table.setSpacingAfter(10f);
                
                table.setWidths(new int[] {30, 10});
                
                table.addCell("Total Amount Gained From Sales");
                cell = new PdfPCell(new Phrase((totalCost) + ""));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                table.addCell(cell);                 
                table.addCell("Total Purchase Cost of Stocks");
                cell = new PdfPCell(new Phrase((totalPurchaseCost) + ""));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                table.addCell(cell); 
                
                cell = new PdfPCell(new Phrase("Difference: "));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                
                table.addCell(cell);
                
                cell = new PdfPCell(new Phrase((totalCost - totalPurchaseCost) + ""));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                table.addCell(cell);                
            }
        } else if (type == 2) { /* Repair */
            table = new PdfPTable(5);
            
            table.setSpacingBefore(10f);
            table.setWidths(new int[] {5, 20, 20, 20, 20});
            table.addCell("#");
            table.addCell("SKU");
            table.addCell("Product Name");
            table.addCell("Repair Verdict");
            table.addCell("Total Cost");

            List<Item> items = DaoFactory.getInstance().getItemDao().getAllItemsWithRepair(startDate, endDate);
            
            int i = 0;
            float totalCost = 0;
            for(Item item: items) {
                    table.addCell(new PdfPCell(new Phrase(++i+""))).setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(item.getSerial());
                    table.addCell(item.getProduct().getName());
                    String verdict = item.getRepairDetail().getVerdict();
                    table.addCell((verdict == null || verdict.isEmpty()) ? "In Repair" : verdict);
                    if(item.getRepairDetail().getLaborCost() != null) {
                        table.addCell(new PdfPCell(new Phrase((item.getRepairDetail().getLaborCost() + item.getRepairDetail().getPartsCost() + item.getRepairDetail().getAdditionalCost()) + ""))).setHorizontalAlignment(Element.ALIGN_RIGHT);
                        totalCost += (item.getRepairDetail().getLaborCost() + item.getRepairDetail().getPartsCost() + item.getRepairDetail().getAdditionalCost());

                    } else {
                        table.addCell("");
                    }
            }
            
            
                PdfPCell cell = new PdfPCell(new Phrase("Total: "));
                cell.setColspan(4);
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                
                table.addCell(cell);
                cell = new PdfPCell(new Phrase((totalCost) + ""));
                cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                table.addCell(cell); 
        } else if (type == 3) { /* Performance */
            par1 = new Paragraph("Best-Selling Products");
            par1.setAlignment(Element.ALIGN_CENTER);
            document.add(par1);

            products = productDao.getBestSellingProducts(startDate, endDate);
            int totalItems = 0;

            table = new PdfPTable(3);
            table.setSpacingBefore(10f);
            table.addCell("#");
            table.addCell("Product");
            table.addCell("Numbers of items sold");

            for (int i = 0, size = products.size(); i < size; i++) {
                p = products.get(i);
                table.addCell((i + 1) + "");
                table.addCell(p.getName());
                table.addCell(p.getAvailableStocks() + "");
                totalItems += p.getAvailableStocks();
            }
            table.addCell("");
            table.addCell("Total Number of items sold:");
            table.addCell(totalItems + "");

            document.add(table);

            par1 = new Paragraph("Underperforming Products");
            par1.setAlignment(Element.ALIGN_CENTER);
            document.add(par1);

            products = productDao.getUnderperformingProducts();

            table = new PdfPTable(2);
            table.setSpacingBefore(10f);
            table.addCell("#");
            table.addCell("Product");
            

            for (int i = 0, size = products.size(); i < size; i++) {
                p = products.get(i);
                table.addCell((i + 1) + "");
                table.addCell(p.getName());
            }
        } else if (type == 4) { /* In and Out */

            List<Staff> staffs = DaoFactory.getInstance().getStaffDao().findAll();

                            table = new PdfPTable(4);
                table.setSpacingBefore(10f);
                
                table.addCell("Product");
                table.addCell("Serial #");
                table.addCell("Staff");
                table.addCell("Type");
            
            for (Staff staff : staffs) {

                for (Batch batch : DaoFactory.getInstance().getBatchDao().findByStaff(staff, startDate, endDate)) {
                    for (Item item : batch.getItems()) {
                        table.addCell(item.getProduct().getName());
                        table.addCell(item.getSerial());
                        table.addCell(staff.getName());
                        table.addCell("in");
                    }
                }
                                
                for (Order order : DaoFactory.getInstance().getOrderDao().findByStaff(staff, startDate, endDate)) {
                    for (Item item : order.getItems()) {
                        table.addCell(item.getProduct().getName());
                        table.addCell(item.getSerial());
                        table.addCell(staff.getName());
                        table.addCell("out");
                    }
                }
                
            }
        } else if (type == 5) { /* Sales */
            table = new PdfPTable(4);
            table.setSpacingBefore(10f);
            table.addCell("Product");
            table.addCell("SKU");
            table.addCell("Customer");
            table.addCell("Customer Contact Number");

            for (Item item : DaoFactory.getInstance().getItemDao().getAllSoldItems(startDate, endDate)) {
                table.addCell(item.getProduct().getName());
                table.addCell(item.getSerial());
                if(item.getPurchaseDetail().getCustomer() != null) {
                    table.addCell(item.getPurchaseDetail().getCustomer().getName());
                    table.addCell(item.getPurchaseDetail().getCustomer().getPhoneNumber());
                } else  {
                    table.addCell("none");
                    table.addCell("none");
                }
            }
        }

        document.add(table);
        document.close();

        return new File(filename);
    }
}
